﻿using System;
using System.IO;
using System.Windows.Forms;
using RSuite.Services;

namespace RSuite.R2.Services
{
    public class MainLocalService : LocalServiceBase
    {
        protected override object Process(string method, dynamic parameters, string taskId)
        {
            switch (method)
            {
                case "open":
                    return this.Open(parameters);
                case "save":
                    return this.Save(parameters["filename"], parameters["review"]);
                default:
                    return null;
            }
        }

        private object Open(string filename)
        {
            var dialog = new OpenFileDialog();
            dialog.FileName = filename;
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return string.Empty;
            }

            if (Path.GetExtension(dialog.FileName).ToLower() == ".rvw")
            {
                return new
                {
                    filename = dialog.FileName,
                    review = File.ReadAllText(dialog.FileName)
                };
            }
            else
            {
                return new
                {
                    filename = "",
                    review = base.ToJSON(new
                    {
                        codefile = Path.GetFileName(dialog.FileName),
                        code = File.ReadAllText(dialog.FileName),
                        reviewDate = DateTime.Today.ToString("yyyy/MM/dd HH:mm:ss")
                    })
                };
            }
        }

        private object Save(string filename, string data)
        {
            if (string.IsNullOrEmpty(filename))
            {
                var dialog = new SaveFileDialog();
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return string.Empty;
                }
                filename = dialog.FileName;
            }

            File.WriteAllText(filename, data);

            return filename;
        }
    }
}